package com.huike.clues.service.impl;

import com.huike.clues.service.ISysFileService;
import com.huike.common.config.MinioConfig;
import com.huike.common.core.domain.AjaxResult;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService {


    @Autowired
    private MinioConfig minioConfig;



    /**
     * 文件上传至Minio
     */
    @Override
    public AjaxResult upload(MultipartFile file) throws Exception {


        //创建Minio的连接对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();
        //判断文件存储的桶是否存在
            String bucketName = minioConfig.getBucketName();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            //SetBucketPolicyArgs.builder().bucket(bucketName).config("q").build();
        } else {
            System.out.println("==============Bucket already exists===============");
        }
        //操作文件，文件上传
        String filename = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String objectName = sdf.format(new Date()) + "/" + filename;
        System.out.println("objectName = " + objectName);
        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        //封装访问的url给前端
        String url = minioConfig.getEndpoint() + ":" + minioConfig.getPort() + "/" + bucketName + "/" + objectName;
        filename = bucketName + "/" + objectName;
        System.out.println("url = " + url);
        AjaxResult result =AjaxResult.success();
        //HashMap<String, Object> map = new HashMap<String, Object>();
        result.put("url",url);
        result.put("fileName",filename);
        result.put("code",200);
     /*   map.put("url",url);
        map.put("fileName",filename);
        map.put("code",200);
        map.put("msg","操作成功");*/

        return result;
    }
}


